package com.xcoder.leetcode;


import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/valid-parentheses/
 */
public class _20_有效的括号 {

    /**
     * 栈
     */
    public boolean isValid(String s) {
        if (s == null) {
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0, size = s.length(); i < size; i++) {
            char c = s.charAt(i);
            if (c == '{' || c == '[' || c == '(') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                char top = stack.pop();
                if (top == '{' && c != '}') return false;
                if (top == '[' && c != ']') return false;
                if (top == '(' && c != ')') return false;
            }
        }
        return stack.isEmpty();
    }

    /**
     * Map
     */
    public boolean isValidWithMap(String s) {
        if (s == null) {
            return false;
        }
        Map<Character, Character> map = new HashMap<>();
        map.put('{', '}');
        map.put('[', ']');
        map.put('(', ')');

        Stack<Character> stack = new Stack<>();
        for (int i = 0, size = s.length(); i < size; i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                char value = map.get(stack.pop());
                if (c != value) return false;
            }
        }
        return stack.isEmpty();
    }
}
